var express = require("express");
var router = express.Router();
const shortid = require("shortid");
const moment = require("moment");
const low = require("lowdb");
const FileSync = require("lowdb/adapters/FileSync");
const AccountModel = require("../models/AccountModel");

const adapter = new FileSync(__dirname + "/../data/db.json");
const db = low(adapter);

router.get("/account", async function (req, res, next) {
  AccountModel.find()
    .sort({ time: -1 })
    .exec((err, accounts) => {
      if (err) {
        return res.status(500).send("查询失败");
      }

      accounts = accounts
        .map((o) => o._doc)
        .map((o) => ({
          ...o,
          time: moment(o.time).format("YYYY-MM-DD"),
        }));
      res.render("list", { accounts });
    });
});

router.get("/account/create", function (req, res, next) {
  res.render("create");
});

router.post("/account", function (req, res, next) {
  AccountModel.create(
    {
      ...req.body,
      // 字符串转对象，对象转时间对象
      time: moment(req.body.time).toDate(),
    },
    (err) => {
      if (err) {
        return res.status(500).send("插入失败");
      }
      res.render("success", { msg: "添加成功哦~~~~", url: "/account" });
    }
  );
});

router.get("/account/:id", function (req, res, next) {
  // mongodb内部会间将_id赋值给一个隐藏的id字段
  const id = req.params.id;
  AccountModel.deleteOne({ id }, (err) => {
    if (err) {
      return res.status(500).send("删除失败");
    }
    res.render("success", { msg: "删除成功哦~~~~", url: "/account" });
  });
});

module.exports = router;
